package com.lhg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.lhg.framework.influx.InfluxRepository;
import com.lhg.mapper.QuotaMapper;
import com.lhg.pojo.dto.DeviceDTO;
import com.lhg.pojo.dto.DeviceInfoDTO;
import com.lhg.pojo.dto.QuotaDTO;
import com.lhg.pojo.dto.QuotaInfo;
import com.lhg.pojo.entity.Quota;
import com.lhg.service.QuotaService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 刘华桂
 */
@Service
public class QuotaServiceImpl extends ServiceImpl<QuotaMapper, Quota> implements QuotaService {
    @Autowired
    private InfluxRepository influxRepository;
    @Override
    public List<QuotaInfo> getLastQuotaList(String deviceId) {
        String ql="select last(value),* from quota where deviceId='"+ deviceId+"' group by quotaId";
        return influxRepository.query(ql,QuotaInfo.class);
    }

    @Override
    public List<String> getAllSubject() {
        QueryWrapper<Quota> wrapper = new QueryWrapper<>();
        wrapper.lambda().select(Quota::getSubject);

        return this.list(wrapper).stream().map(Quota::getSubject).collect(Collectors.toList());
    }

    @Override
    public DeviceInfoDTO analysis(String topic, Map<String, Object> payloadMap) {

        // 按主题查询对的指标列表
        List<Quota> quotaList = baseMapper.selectBySubject(topic);
        if (quotaList.size() == 0){
            return null;
        }

        // 判断出设备唯一编码的key
        String snKey = quotaList.get(0).getSnKey();
        if (Strings.isNullOrEmpty(snKey)){
            System.out.println("snKey = " + snKey);
            return null;
        }

        // 判断设备唯一编码是否存在
        String deviceId = (String) payloadMap.get(snKey);
        if (Strings.isNullOrEmpty(deviceId)){
            System.out.println("deviceId = " + deviceId);
            return null;
        }
        DeviceDTO deviceDTO=new DeviceDTO();
        deviceDTO.setDeviceId(deviceId);

        //3.封装指标列表  :  循环我们根据主题名称查询得指标列表，到报文中提取，如果能够提到，进行封装
        List<QuotaDTO> quotaDTOList= Lists.newArrayList();
        for( Quota quota:quotaList ){
            //指标key
            String quotaKey = quota.getValueKey();

            if( payloadMap.containsKey(quotaKey) ){
                QuotaDTO quotaDTO=new QuotaDTO();
                //复制指标配置信息
                BeanUtils.copyProperties(quota, quotaDTO);
                quotaDTO.setQuotaName(quota.getName());

                //指标值封装
                //指标分为两种  1.数值  2.非数值（string boolean）
                //1.数值   value 存储数值  stringValue :存储数值字符串
                //2.非数值  value 0   stringValue:内容

                //如果是非数值
                if( "String".equals(quotaDTO.getValueType()) || "Boolean".equals(quotaDTO.getValueType()) ){
                    quotaDTO.setStringValue((String) payloadMap.get(quotaKey));
                    quotaDTO.setValue(0d);
                }else{
                    //如果是数值
                    if (!(payloadMap.get(quotaKey) instanceof String)) {
                        quotaDTO.setValue( Double.valueOf( payloadMap.get(quotaKey) +"" )  );
                        quotaDTO.setStringValue( quotaDTO.getValue()+"" );
                    } else {
                        quotaDTO.setValue( Double.valueOf(   (String) payloadMap.get(quotaKey)  ) );
                        quotaDTO.setStringValue( (String) payloadMap.get(quotaKey)  );
                    }
                    quotaDTO.setDeviceId( deviceId );

                }
                quotaDTOList.add(quotaDTO);
            }
        }

        //4.封装设备+指标列表返回
        DeviceInfoDTO deviceInfoDTO=new DeviceInfoDTO();
        deviceInfoDTO.setDevice(deviceDTO);
        deviceInfoDTO.setQuotaList(quotaDTOList );

        // 封装指标列表信息
        return deviceInfoDTO;
    }

    @Override
    public void saveQuotaToInflux(List<QuotaDTO> quotaDTOList) {
        for(QuotaDTO quotaDTO:quotaDTOList){
            QuotaInfo quotaInfo=new QuotaInfo();
            BeanUtils.copyProperties(quotaDTO,quotaInfo);//拷贝属性
            quotaInfo.setQuotaId(quotaDTO.getId()+"");//指标id
            influxRepository.add(quotaInfo);
        }
    }

    @Override
    public IPage<Quota> queryNumberQuota(Long page, Long pageSize) {
        Page<Quota> pageResult = new Page<>(page,pageSize);
        LambdaQueryWrapper<Quota> wrapper = new LambdaQueryWrapper<>();
        wrapper
                .eq(Quota::getValueType,"Long")
                .or()
                .eq(Quota::getValueType,"Integer")
                .or()
                .eq(Quota::getValueType,"Double");
        return this.page(pageResult,wrapper);
    }

    @Override
    public IPage<Quota> queryPage(Long page, Long pageSize, String quotaName) {
        Page<Quota> pageResult = new Page<>(page,pageSize);
        LambdaQueryWrapper<Quota> wrapper = new LambdaQueryWrapper<>();
        if(!Strings.isNullOrEmpty(quotaName)){
            wrapper.like(Quota::getName,quotaName);
        }

        return this.page(pageResult,wrapper);
    }
}
